async function uploadChunks(chunks, file) {
    const totalChunks = chunks.length;
    const fileHash = await calculateFileHash(file); // 计算文件哈希
    const uploadedChunks = [];

    for (let i = 0; i < totalChunks; i++) {
        const chunk = chunks[i];
        const formData = new FormData();
        formData.append('file', chunk.blob);
        formData.append('hash', fileHash);
        formData.append('index', chunk.index);
        formData.append('total', totalChunks);

        try {
            await uploadChunk(formData);
            uploadedChunks.push(chunk.index);
            console.log(`分片 ${chunk.index + 1}/${totalChunks} 上传成功`);
        } catch (error) {
            console.error(`分片 ${chunk.index + 1}/${totalChunks} 上传失败`, error);
            // 可以添加重试逻辑
        }
    }

    // 所有分片上传完成后，通知服务器合并
    await mergeChunks(fileHash, totalChunks);
    console.log('所有分片上传完成，开始合并');
}

async function calculateFileHash(file) {
    return new Promise((resolve) => {
        const spark = new SparkMD5.ArrayBuffer();
        const fileReader = new FileReader();
        const chunkSize = 5 * 1024 * 1024; // 2MB
        let currentChunk = 0;

        fileReader.onload = function (e) {
            spark.append(e.target.result);
            currentChunk += chunkSize;
            if (currentChunk < file.size) {
                loadNext();
            } else {
                resolve(spark.end());
            }
        };

        fileReader.onerror = function () {
            console.error('文件读取失败');
            resolve(null);
        };

        function loadNext() {
            const start = currentChunk;
            const end = Math.min(start + chunkSize, file.size);
            fileReader.readAsArrayBuffer(file.slice(start, end));
        }

        loadNext();
    });
}

async function uploadChunk(formData) {
    return fetch('/upload', {
        method: 'POST',
        body: formData
    }).then(response => {
        if (!response.ok) {
            throw new Error('上传失败');
        }
        return response.json();
    });
}

async function mergeChunks(fileHash, totalChunks) {
    return fetch('/merge', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            hash: fileHash,
            total: totalChunks
        })
    }).then(response => {
        if (!response.ok) {
            throw new Error('合并失败');
        }
        return response.json();
    });
}

document.getElementById('fileInput').addEventListener('change', async () => {
    const file = document.getElementById('fileInput').files[0];
    console.log('拿到文件:', file);
    console.time('上传文件计时');

    try {
        const chunks = await cutFile(file);
        console.log('文件切割完成', chunks);
        await uploadChunks(chunks, file);
        console.log('文件上传完成');
    } catch (error) {
        console.error('文件处理失败', error);
    } finally {
        console.timeEnd('上传文件计时');
    }
});